<template>
    <div class="form-button-group margin-bottom-20">
        <router-link :to="{ name: 'InfoDetail' }">
            <el-button type="danger">新增</el-button>
        </router-link>
    </div>
    <el-form :inline="true" ref="searchFormRef" :model="request_data">
        <el-form-item label="类别" prop="category_id">
            <el-cascader v-model="request_data.category_id" :props="category_props"
                :options="categoryData.category_options" filterable clearable style="width: 320px;" />
        </el-form-item>
        <el-form-item label="关键词" prop="key">
            <el-select v-model="request_data.key" placeholder="请选择">
                <el-option v-for="item in keywords.options" :key="item.value" :value="item.value"
                    :label="item.label"></el-option>
            </el-select>
        </el-form-item>
        <el-form-item prop="value">
            <el-input v-model.trim="request_data.value" placeholder="请输入关键词" v-model="keywords.value" clearable />
        </el-form-item>
        <el-form-item>
            <el-button type="danger" @click="handleSearch">搜索</el-button>
            <el-button type="default" @click="handleReset">重置</el-button>
        </el-form-item>
    </el-form>
    <el-table :data="infoList" border style="width: 100%" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" />
        <el-table-column label="标题" prop="title" width="200" />
        <el-table-column label="类别" prop="category.name" width="100" />
        <el-table-column label="创建时间" prop="created_time" width="200" />
        <el-table-column label="发布状态" width="120px">
            <template #default="scope">
                <el-switch v-model="scope.row.status" :active-value="1" :inactive-value="0" :loding="scope.row.loding"
                    @change="handleChangeStatus($event, scope.row)" />
            </template>
        </el-table-column>
        <el-table-column label="发布时间" prop="release_time" width="200" />
        <el-table-column label="操作">
            <template #default="scope">
                <el-button size="small" @click="handleEdit(scope.row.id)">
                    编辑
                </el-button>
                <el-button size="small" type="danger" @click="handleDelete(scope.row.id)">
                    删除
                </el-button>
            </template>
        </el-table-column>
    </el-table>
    <el-row class="margin-top-20">
        <el-col :span="6">
            <el-button type="danger" :disabled="!row_data_id" @click="handleDelete(row_data_id)">批量删除</el-button>
        </el-col>
        <el-col :span="18">
            <el-pagination class="pull-right" v-model:current-page="request_data.pageIndex"
                v-model:page-size="request_data.pageSize" :page-sizes="[10, 20, 30, 50]" background small
                layout="total, sizes, prev, pager, next, jumper" :total="total" @size-change="handleSizeChange"
                @current-change="handleCurrentChange" />
        </el-col>
    </el-row>
</template>

<script setup>
import { ref, reactive, toRefs, onBeforeMount } from 'vue'
import { useRouter } from 'vue-router'
import useStore from '@/store'
import { useCategoryHook } from '@/hooks/categoryHook'

const searchFormRef =ref(null)
const router = useRouter()
const store = useStore()
const { categoryData, getAllCategory } = useCategoryHook()

// const multipleSelection = ref([])

const data = reactive({
    keywords: {
        options: [
            {
                label: '标题',
                value: 'title'
            },
            {
                label: '内容',
                value: 'content'
            }
        ],
        value: ''
    },
    category_props: {
        label: 'name',
        value: 'id'
    },
    infoList: [],
    total: 0,
    request_data: {
        key: 'title',
        value: '',
        pageIndex: 1,
        pageSize: 10,
        category_id: []
    },
    row_data_id: ''
})

const { total, request_data, infoList, row_data_id, category_props, keywords } = toRefs(data)

const getInfoList = async (isSearch = false) => {
    const res = await store.info.getInfoListAction(format_params(isSearch))
    const res_data = res.data
    infoList.value = res.data.rows
    total.value = res_data.count
}

onBeforeMount(async () => {
    await getInfoList()
    await getAllCategory()
})

const handleSelectionChange = (val) => {
    console.log('handleSelectionChange val', val);
    if (val && val.length > 0) {
        const ids = val.map(item => item.id)
        row_data_id.value = ids.join()
    } else {
        row_data_id.value = ''
    }
    multipleSelection.value = val
}

const handleSizeChange = (val) => {
    console.log(`${val} items per page`)
    request_data.value.pageSize = val
    request_data.value.pageIndex = 1
    getInfoList()
}
const handleCurrentChange = (val) => {
    console.log(`current page: ${val}`)
    request_data.value.pageIndex = val
    getInfoList()
}

const handleChangeStatus = async (value, data) => {
    data.loading = true
    data.status = !data.status
    try {
        const res = await store.info.changeInfoStatusAction({ id: data.id, data: { status: value } })
        ElMessage.success(res.msg)
        await getInfoList()
        data.status = value
    } finally {
        data.loading = false
    }
}

const handleDelete = (id) => {
    ElMessageBox.confirm(
        '确定要删除当前信息吗?',
        '提示',
        {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning',
        }
    )
        .then(async () => {
            const res = await store.info.deleteInfoAction({ id, data: {} })
            ElMessage.success(res.msg)
            await getInfoList()
        })
}

const handleEdit = (id) => {
    console.log('handleEdit id', id);
    router.push({
        name: 'InfoDetail',
        query:{ id }
    })

}

//判断是否有输入过滤条件
const hasEnterFilter = () => {
    const { category_id, value } = request_data.value
    return (category_id != null && category_id.length > 0) || value.length > 0
}

// 对参数进行格式化
const format_params = (isSearch = false) => {
    let { category_id, key, value, pageIndex, pageSize } = request_data.value
    const params = {}
    if (isSearch && hasEnterFilter) {
        if (category_id != null && category_id.length > 0) {
            params.category_id = category_id[category_id.length - 1]
        }
        if (value.length > 0) {
            params.keywords_key = key
            params.keywords_value = value
        }
        params.keywords_key = data.keywords.key
        params.keywords_value = data.keywords.value
    }
    params.pageIndex = pageIndex
    params.pageSize = pageSize
    return params
}

const handleSearch = async () => {
    if (!hasEnterFilter()) {
        ElMessageBox.confirm(
            '没有输入搜索类别和关键词，是否要继续搜索？',
            '提示',
            {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning',
            }
        )
            .then(async () => {
                await getInfoList()

            })
    } else {
        await getInfoList(true)
    }
}

const handleReset = () =>{
    searchFormRef.value.resetFields()
}
</script>

<style lang="scss" scoped></style>